package com.haochu.novel.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.example.testnovel.R;
import com.haochu.novel.db.DBHelper;
import com.haochu.novel.util.Constants;
import com.haochu.novel.util.MeasureUtil;
import com.haochu.novel.util.SpeekUitl;

/**
 * @author fuhuichao
 * 2017年6月20日17:13:40
 * 小说内容
 */
@SuppressLint("ClickableViewAccessibility")
public class BookContentActivity extends Activity {

	// 自定义view
	BookContentView mBookContentView;
	// 文字工具工厂
	private BookFactory bookFactory;
	// 文字当前页的位图
	private Bitmap mCurPageBitmap, mNextPageBitmap;
	// 页面背景图片
	private Bitmap backGroundBitmap;
	// 文字当前页的canvas
	private Canvas mCurCanvas, mNextCanvas;
	// 屏幕尺寸
	int screenWidth, screenHeight;
	// 点击自定义view时的坐标
	float touchX, touchY, touchOldX, touchOldY;
	// 点击时Y轴方向上的有效区域
	float partUpY, partDownY;
	// 参数存储类
	private SharedPreferences preference;
	private SharedPreferences.Editor editor;
	// 菜单栏
	private PopupWindow menuPopup;
	// 菜单栏view
	private View menuPopupView;
	// 菜单栏button
	private Button btnFontSizeBigger, btnFontSizeSmaller, btnCategory, btnTTS;
	// 数据库工具
	private DBHelper dbHelper;
	// 小说id，假设为1
	private int bookId = 1;
	// 语音合成工具
	private SpeekUitl speekUtil;
	// 吐司
	private Toast mToast;
	// 缓冲进度
	private int mPercentForBuffering = 0;
	// 播放进度
	private int mPercentForPlaying = 0;
	// 标记播放或者暂停
	private boolean playOrPause = true;
	// 播放按钮图标
	private Drawable drawablePlay;
	// 暂停按钮图标
	private Drawable drawablePause;
	
	@SuppressLint("ShowToast") 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//设置无标题  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        //设置全屏  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        
        setContentView(R.layout.textview_book_content);
		mBookContentView = (BookContentView) findViewById(R.id.mBookContentView);
		
		// 监听触摸操作
		mBookContentView.setOnTouchListener(new mViewTouchListener());
		
		// 初始化吐司
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		
		// 初始化popup
		initPopup();
		
		// 获取屏幕尺寸
		screenWidth = MeasureUtil.getScreenWidth(this);
		screenHeight = MeasureUtil.getScreenHeight(this);
		
		// 计算Y轴方向有效区域（上下浮动十分之二）
		partUpY = screenHeight / 2 * 0.8f;
		partDownY = screenHeight / 2 * 1.2f;
		
		// 获取页面背景图片
		backGroundBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg);
		backGroundBitmap = Bitmap.createScaledBitmap(backGroundBitmap, screenWidth, screenHeight, true);
		
		// 创建位图，初始化canvas
		mCurPageBitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
		mNextPageBitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
		mCurCanvas = new Canvas(mCurPageBitmap);
		mNextCanvas = new Canvas(mNextPageBitmap);
		
		// 将位图传递给自定义view
		mBookContentView.setmCurPageBitmap(mCurPageBitmap, mNextPageBitmap);
		
		// 开始启动工厂
		preference = getSharedPreferences(Constants.REFERENCE_FILENAME, MODE_PRIVATE);
		bookFactory = new BookFactory(screenWidth, screenHeight, preference);
		
		// 创建数据库工具
		dbHelper = new DBHelper(this);
		dbHelper.addBook(Constants.BOOKPATH, "重生完美");
		bookFactory.setDBHelper(dbHelper);
		bookFactory.setBookId(bookId);

		// 加载后就开始智能断章和分页
		getCategories();
		
		// 传递页面背景图片
		bookFactory.setBackGroundBitmap(backGroundBitmap);
		
		// 画一页内容
		bookFactory.pageNext();
		bookFactory.doDraw(mCurCanvas);
		
		// 初始语音工具
		drawablePlay = getResources().getDrawable(R.drawable.play);
		drawablePause = getResources().getDrawable(R.drawable.pause);
		speekUtil = new SpeekUitl(BookContentActivity.this, bookFactory);
	}
	
	
	/**
	 * 初始化popup
	 */
	@SuppressLint("InflateParams") 
	public void initPopup(){
		menuPopupView = getLayoutInflater().inflate(R.layout.pop_menu_book_content, null);
		menuPopup = new PopupWindow(menuPopupView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		menuPopup.setAnimationStyle(R.style.popwin_anim_style);
		menuPopup.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
		
		// 初始化菜单栏按钮
		btnFontSizeBigger = (Button) menuPopupView.findViewById(R.id.btnFontSizeBigger);
		btnFontSizeSmaller = (Button) menuPopupView.findViewById(R.id.btnFontSizeSmaller);
		btnCategory = (Button) menuPopupView.findViewById(R.id.btnCategory);
		btnTTS = (Button) menuPopupView.findViewById(R.id.btnTTS);
		
		// 设置按钮click监听
		mViewClickListener mViewClickListener = new mViewClickListener();
		btnFontSizeBigger.setOnClickListener(mViewClickListener);
		btnFontSizeSmaller.setOnClickListener(mViewClickListener);
		btnCategory.setOnClickListener(mViewClickListener);
		btnTTS.setOnClickListener(mViewClickListener);
	}
	
	/**
	 * 加载后就获取一次目录
	 */
	public void getCategories(){
		
		// 开始智能断章 
		new Thread(new Runnable() {
			@Override
			public void run() {
				bookFactory.startAnalyzeCategories();
			}
		}).start();

//		// 开始计算分页
//		new Thread(new Runnable() {
//			@Override
//			public void run() {
//				bookFactory.startPagination();
//				
//				// 发消息刷新页面
//				refreshCurPage();
//			}
//		}).start();
		
//		// 刷新智能断章的进度
//		new Thread(new Runnable() {
//			@Override
//			public void run() {
//            	float percent = 0f;
//            	Message m = null;
//            	Bundle b = null;
//            	while(percent < 100){
//            		// 获取进度百分比
//            		percent = bookFactory.getCategoryPercent();
//
//            		// 发送消息
//            		b = new Bundle();
//            		b.putFloat("p", percent);
//            		m = new Message();
//            		m.setData(b);
//            		m.what = 1;
//            		mHandler.sendMessage(m);
//            		
//            		// 每次刷新间隔0.5秒
//            		try {
//            			Thread.sleep(500);
//            		} catch (InterruptedException e) {
//            			e.printStackTrace();
//            		}
//            	}
//			}
//		}).start();
	}
	
	/**
	 * 	自定义view的touch监听
	 */
	class mViewTouchListener implements View.OnTouchListener{
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			
			if(v == mBookContentView){
				touchX = event.getX();
				touchY = event.getY();
				switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						touchOldX = touchX;
						touchOldY = touchY;
						break;
					case MotionEvent.ACTION_UP:
						if(touchX > touchOldX){
							// 往右滑
	
						}else if(touchX < touchOldX){
							// 往左滑
							
						}else if(touchY < partUpY){
							// 点击上区域
							if(bookFactory.isPageFirst()){
								showTip(R.string.first_page);
							}else{
								doPagePre();
							}
						}else if(touchY > partDownY){
							// 点击下区域
							if(bookFactory.isPageLast()){
								showTip(R.string.last_page);
							}else{
								doPageNext();
							}
						}else{
							// 点击中间区域， 弹出菜单
							menuPopup.showAtLocation(mBookContentView, Gravity.BOTTOM, 0, 0);
						}
						break;
					default:
						break;
				}
			}
			return true;
		}
	}
	
	/**
	 *	自定义popup的click监听
	 */
	class mViewClickListener implements View.OnClickListener{
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			// 加大字体
			case R.id.btnFontSizeBigger:
				if(bookFactory.changeTextSize(1)){
					refreshCurPage();
				}
				break;
			// 减小字体
			case R.id.btnFontSizeSmaller:
				if(bookFactory.changeTextSize(0)){
					refreshCurPage();
				}
				break;
			// 打开目录
			case R.id.btnCategory:
				startActivityForResult(new Intent(BookContentActivity.this, BookCategoryActivity.class), Constants.REQUEST_CODE_ACTIVITY);
				break;
			// 打开语音
			case R.id.btnTTS:
				if(playOrPause){
					playOrPause = false;
					speekUtil.startSpeaking();
					btnTTS.setCompoundDrawablesWithIntrinsicBounds(null, drawablePause, null, null);
				}else{
					playOrPause = true;
					speekUtil.stopSpeaking();
					btnTTS.setCompoundDrawablesWithIntrinsicBounds(null, drawablePlay, null, null);
				}
				break;
			default:
				break;
			}
		}
	}
	

	
	/**
	 * 接收其他activity传递过来的参数
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 关闭菜单popup
		menuPopup.dismiss();
		if(requestCode == Constants.REQUEST_CODE_ACTIVITY){
			switch (resultCode) {
			// 从目录列表跳转过来
			case Constants.RESULT_CODE_CATEGORY:
				
				// 获取点击的目录下标
				int position = data.getExtras().getInt(Constants.RESULT_KEY_CATEGORY);
				int mbbIndex = bookFactory.getCategories().get(position).getPosition();
				
				editor = preference.edit();
				editor.putInt(Constants.PREFERENCE_KEY_MBBINDEX, mbbIndex);
				editor.commit();
				
				// 刷新当前页面
				refreshCurPage();
				
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 传递消息，刷新小说当前页面UI
	 */
	@SuppressLint("HandlerLeak") 
	private Handler mHandler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            super.handleMessage(msg);  
            switch (msg.what) {  
            case 0:  
            	mBookContentView.invalidate();
                break;
//            case 1:
//            	bookFactory.drawPercent(msg.getData().getFloat("p") + "%", mCurCanvas);
//            	mBookContentView.invalidate();
//            	break;
            default:  
                break;  
            }  
        }  
    };  
	
    /**
     * 向前翻一页
     */
    public void doPagePre(){
    	bookFactory.pagePre();
		bookFactory.doDraw(mCurCanvas);
		speekUtil.resetIndex();
		mHandler.sendEmptyMessage(0);
    }
    
    /**
     * 向后翻一页
     */
    public void doPageNext(){
    	bookFactory.pageNext();
		bookFactory.doDraw(mCurCanvas);
		speekUtil.resetIndex();
		mHandler.sendEmptyMessage(0);
    }
    
    /**
     * 改变配置后刷新当前页面
     */
    public void refreshCurPage(){
    	bookFactory.initFactory();
		bookFactory.pageNext();
		bookFactory.doDraw(mCurCanvas);
		mHandler.sendEmptyMessage(0);
    }
    
    /**
     * 弹出toast
     */
    public void showTip(final String str) {
		mToast.setText(str);
		mToast.show();
	}
    
    /**
     * 弹出toast
     */
    public void showTip(final int resId) {
    	mToast.setText(resId);
    	mToast.show();
    }
    
}
